import { useEffect } from 'react';
import { Select, Space } from 'antd';

import { TjChart, TjCollapse, useTRState, TjDimension } from '@/pages/ETrade/components';
import { TRDefault } from '#/components';

import BaseTable from '../BaseTable';
import { CODE1, getChartOption, computerData } from '../../helper';
import { orderOptions, chartsMap } from '../../constant';
import styles from './index.less';

const Container = ({ order, setOrder, tableData, onChange }) => {
  /** data */
  const [state, setState] = useTRState({
    filters: [], // 详情，已选维度值
    filterOptions: [], // 详情，维度选项
    chartData: null,
  });

  useEffect(() => {
    // 聚合维度处理
    const filters = Array.from({ length: order.length - 1 }, () => 0);
    onChangeFilters(filters);
    setState({ filters });
  }, [tableData]);

  const onChangeFilters = (filters) => {
    // 聚合维度处理
    let _options = [];
    const len = filters.length;
    const fn = (list, lv) => {
      const dataI = filters[lv];
      const { children = [] } = list[dataI] || {};
      if (lv === len) {
        _options[lv] = list;
      } else {
        _options[lv] = list.map((x, idx) => ({ label: x[CODE1], value: idx }));
      }
      lv < len && fn(children, lv + 1);
    };
    // 去掉总合计
    fn(tableData.slice(1), 0);
    // 拿到选项和渲染结果
    const filterOptions = _options.slice(0, -1);
    const chartData = _options?.[_options.length - 1];
    repaint(chartData);
    setState({
      filterOptions,
    });
  };

  //根据筛选参数 重绘图表
  const repaint = async (data) => {
    //计算
    const dataMap = data.map((t) => ({
      ...t,
      ...computerData(t),
    }));
    setState({
      chartData: dataMap,
    });
  };

  const onChangeFilterItem = (lv, idx) => {
    // 当前维度索引更新，子维度索引清0
    let { filters } = state;
    const arrBefore = filters.slice(0, lv + 1);
    const arrAfter = filters.slice(lv + 1).map(() => 0);
    filters = [...arrBefore, ...arrAfter];
    filters[lv] = idx;
    setState({ filters });
    onChangeFilters(filters);
  };

  const { chartData } = state;
  /** render */
  const _getEchartsData = () => {
    const loopData = Object.entries(chartsMap);
    if (!chartData) return <TRDefault type={'empty'} />;
    return (
      <div className={styles.chartsRender}>
        {loopData.map((t, i) => {
          return (
            <div
              key={i}
              style={{
                height: `calc(${Math.floor(100 / loopData.length)}% - 1px)`,
                minHeight: 204,
              }}
            >
              <div className={styles.chartTitle}>{t[0]}</div>
              <div style={{ height: `calc(100% - 36px)` }}>
                <TjChart option={getChartOption(t, chartData)} />
              </div>
            </div>
          );
        })}
      </div>
    );
  };
  return (
    <div className={styles.content}>
      <TjCollapse
        left={
          <>
            <div className={styles.inhead}>
              <Space size={16}>
                {state.filterOptions.map((options, lv) => (
                  <Select
                    key={lv}
                    style={{ minWidth: 140 }}
                    value={state.filters[lv]}
                    options={options}
                    optionFilterProp="label"
                    onChange={(idx) => onChangeFilterItem(lv, idx)}
                    showSearch
                  />
                ))}
              </Space>
            </div>
            {_getEchartsData()}
          </>
        }
        right={
          <>
            <div className={styles.inhead}>
              <TjDimension
                value={order}
                options={orderOptions}
                onChange={(order) => setOrder(order)}
                onPoly={onChange}
              />
            </div>
            <div className={styles.inbody}>
              <BaseTable tableData={tableData} choseValue={repaint} />
            </div>
          </>
        }
        rightStyles={{ width: 952, padding: '20px 24px' }}
      />
    </div>
  );
};

export default Container;
